package cn.neusoft.neusoft_fz.controller;


import cn.neusoft.neusoft_fz.common.ResponseEntity;
import cn.neusoft.neusoft_fz.entity.DeliveryEntity;
import cn.neusoft.neusoft_fz.service.DeliveryOrderService;
import cn.neusoft.neusoft_fz.service.PaymentService;
import cn.neusoft.neusoft_fz.utils.PDFUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import lombok.extern.slf4j.Slf4j;
import org.example.entity.DeliveryOrder;
import org.example.entity.DeliveryPerson;
import org.example.entity.Payment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.math.BigDecimal;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.PrimitiveIterator;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author author
 * @since 2023-06-25
 */
@Slf4j
@RestController
@RequestMapping("/delivery-order")
public class DeliveryOrderController {

    @Autowired
    private DeliveryOrderService deliveryOrderService;

    @Autowired
    private PaymentService paymentService;

    @DeleteMapping("/del/{id}")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity<String> del(@PathVariable String id){
        deliveryOrderService.removeById(id);
        return ResponseEntity.success("删除成功");
    }

    @PostMapping("/add")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity<DeliveryOrder> add(@RequestBody DeliveryOrder deliveryOrder){
        log.info("添加配送单");
        deliveryOrderService.save(deliveryOrder);
        return ResponseEntity.success(deliveryOrder);
    }

    @PutMapping("update")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity<String> update(@RequestBody DeliveryOrder deliveryOrder){
        deliveryOrderService.save(deliveryOrder);
        return ResponseEntity.success("修改成功");
    }

    @GetMapping("/all")
    public ResponseEntity<List<DeliveryEntity>> getAll(){
        List<DeliveryEntity> entities = deliveryOrderService.deliveryEntities();
        return ResponseEntity.success(entities);
    }

    @GetMapping("/all/{subid}")
    public ResponseEntity<List<DeliveryEntity>> getAll(@PathVariable String subid){
        List<DeliveryEntity> deliveryEntities = deliveryOrderService.deliveryEntitiesBySubid(subid);
        return ResponseEntity.success(deliveryEntities);
    }


    @PostMapping(path = "/createPdf", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_PDF_VALUE)
    public byte[] createPdf(@RequestBody DeliveryEntity data) throws Exception {
        log.info(data.toString());
        // 创建一个独一无二的临时文件
        File tempFile = File.createTempFile("delivery-", ".pdf");
        String dest = tempFile.getAbsolutePath();
        new PDFUtils().createDeliveryPdf(dest, data);
        // 确保文件被完全写完
        byte[] pdfBytes = null;
        if (Files.exists(Paths.get(dest))) {
            pdfBytes = Files.readAllBytes(Paths.get(dest));
            log.info("PDF file read successfully. Size: " + pdfBytes.length + " bytes");

            //确保文件在被删除前完全读取
            Files.delete(Paths.get(dest));
            log.info("Temp file deleted successfully.");
        } else {
            log.error("Failed to create PDF, temp file does not exist.");
        }

        return pdfBytes;
    }

    @GetMapping("/byperson/{dpid}")
    public ResponseEntity<List<DeliveryEntity>> getAllByPersonId(@PathVariable String dpid){
        List<DeliveryEntity> list = deliveryOrderService.deliveryEntitiesByDpid(dpid);
        return ResponseEntity.success(list);
    }

    @PostMapping("/startdelivery")
    public ResponseEntity<String> startdelivery(@RequestBody DeliveryOrder deliveryOrder){
        log.info(deliveryOrder.toString());

        UpdateWrapper<DeliveryOrder> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("delivery_order_id", deliveryOrder.getDeliveryOrderId() ) // 使用主键进行匹配
                .set("delivery_status", "进行中"); // 设置要更新的字段名和字段值

        deliveryOrderService.update(null, updateWrapper);

        return ResponseEntity.success("success");
    }

    @PostMapping("/enddelivery")
    public ResponseEntity<String> enddelivery(@RequestBody DeliveryOrder deliveryOrder){
        log.info(deliveryOrder.toString());

        UpdateWrapper<DeliveryOrder> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("delivery_order_id", deliveryOrder.getDeliveryOrderId() ) // 使用主键进行匹配
                .set("delivery_status", "已完成"); // 设置要更新的字段名和字段值

        deliveryOrderService.update(null, updateWrapper);

        BigDecimal paymentAmount = paymentService.getPaymentAmount(String.valueOf(deliveryOrder.getDeliveryOrderId()));

        Payment payment = new Payment();
        payment.setDeliveryOrderId(deliveryOrder.getDeliveryOrderId());
        payment.setPaymentAmount(paymentAmount);
        payment.setPaymentTime(LocalDateTime.now());

        paymentService.save(payment);

        return ResponseEntity.success("success");
    }



}
